<template>
  <!-- 权限表单对话框 -->
  <zy-base-dialog
    :title="dialogTitle"
    v-model:visible="dialogVisible"
    v-model:fullscreen="dialogFullscreen"
    width="600px"
    :close-on-click-modal="false"
    @close="handleDialogClose"
    @cancel="handleDialogClose"
    @submit="handleSubmit"
    :submit-loading="submitLoading"
  >
    <el-form
      ref="authorityFormRef"
      :model="authorityForm"
      :rules="authorityFormRules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="权限名称" prop="authorityName">
        <el-input v-model="authorityForm.authorityName" placeholder="请输入权限名称" />
      </el-form-item>
      <el-form-item label="权限编码" prop="authorityCode">
        <el-input v-model="authorityForm.authorityCode" placeholder="请输入权限编码" />
      </el-form-item>
      <el-form-item label="权限分类" prop="authorityType">
        <el-select
          v-model="authorityForm.authorityType"
          placeholder="请选择权限分类"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="item in authorityTypeOptions"
            :key="item.dictCode"
            :label="item.dictName"
            :value="item.dictCode"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </zy-base-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElForm, ElFormItem, ElInput, ElSelect, ElOption } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { addAuthority, updateAuthority, SysAuthority } from '@/api/system/authority'
// Business 组件已全局注册，无需导入
import { useDict } from '@/utils/dict'
import { isResponseSuccess } from '@/utils/httpStatus'

// Props
interface Props {
  visible: boolean
  authorityData?: SysAuthority
  isEdit?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  authorityData: undefined,
  isEdit: false
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  success: []
}>()

// 响应式数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const dialogFullscreen = ref(false)

const authorityFormRef = ref<FormInstance>()

// 使用字典工具获取权限分类选项
const authorityTypeOptions = useDict('AUTHORITY_TYPE')

// 权限表单
const authorityForm = reactive<SysAuthority>({
  authorityId: undefined,
  authorityName: '',
  authorityCode: '',
  authorityType: ''
})

// 表单验证规则
const authorityFormRules: FormRules = {
  authorityName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  authorityCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 50, message: '权限编码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  authorityType: [{ required: true, message: '请选择权限分类', trigger: 'change' }]
}

// 监听 visible 变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
    if (newVal) {
      dialogTitle.value = props.isEdit ? '编辑权限' : '新增权限'
      if (props.isEdit && props.authorityData) {
        Object.assign(authorityForm, props.authorityData)
      } else {
        resetAuthorityForm()
      }
    }
  },
  { immediate: true }
)

// 监听 dialogVisible 变化，同步到父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 提交表单
const handleSubmit = async () => {
  if (!authorityFormRef.value) return

  try {
    await authorityFormRef.value.validate()
    submitLoading.value = true

    let result
    if (authorityForm.authorityId) {
      result = await updateAuthority(authorityForm.authorityId, authorityForm)
      if (isResponseSuccess(result)) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        emit('success')
      } else {
        ElMessage.error('更新失败')
      }
    } else {
      result = await addAuthority(authorityForm)
      if (isResponseSuccess(result)) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        emit('success')
      } else {
        ElMessage.error('新增失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置权限表单
const resetAuthorityForm = () => {
  Object.assign(authorityForm, {
    authorityId: undefined,
    authorityName: '',
    authorityCode: '',
    authorityType: ''
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetAuthorityForm()
  if (authorityFormRef.value) {
    authorityFormRef.value.resetFields()
  }
}
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
